package com.emmmya.ocs.modules.system.controller;

/**
 * @description: 菜单控制层 用于页面跳转
 * @author: 咕噜肉IT小店-黑医
 * @createDate: 2020-11-16
 * @version: 1.0
 */

import com.emmmya.ocs.modules.system.annotation.OperateLog;
import com.emmmya.ocs.common.entity.LayUITree;
import com.emmmya.ocs.common.utils.ResultUtil;
import com.emmmya.ocs.common.vo.Result;
import com.emmmya.ocs.modules.system.entity.*;
import com.emmmya.ocs.modules.system.service.*;
import com.emmmya.ocs.modules.system.utils.LayuiTreeUtils;
import com.emmmya.ocs.modules.system.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component
@RequestMapping("system")
public class MenuController {
    @Autowired
    MenuService menuService;

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    PermissionsService permissionsService;

    /**
     * 字典
     */
    @Autowired
    DictService dictService;

    /**
     * 字典数据
     */
    @Autowired
    DictDataService dictDataService;

    /**
     * 定时任务
     */
    @Autowired
    TimedTaskService timedTaskService;


    @Autowired
    private UserUtils userUtils;

    /**
     * 将系统对象转layui的tree工具
     */
    @Autowired
    LayuiTreeUtils layuiTreeUtils;

    @RequestMapping("/user")
    public String user(){
        return "admin2/system/sys-user";
    }

    @RequestMapping("/userEditUI")
    public String userEditUI(@RequestParam(value="userId",required = false)Long userId,Model model){
        if(userId!=null){
            User user = userService.get(userId);
            model.addAttribute("user",user);
        }

        return "admin2/system/user/user-edit";
    }


    //系统菜单管理页面
    @RequestMapping("/sysMenu")
    public String sysMenu(Model mv) {
        List<Menu> menus = menuService.findByLevel(1);
        System.out.println(menus);
        mv.addAttribute("menus",menus);
        return "admin2/system/sys-menu";
    }

    //跳转到菜单添加/修改页面
    @RequestMapping("/menu-add")
    public String menuAdd(Model mv) {
        List<Menu> menus = menuService.findByLevel(1);
        mv.addAttribute("menus",menus);
        return "admin2/system/menu/menu-add";
    }

    //配置菜单权限
    @GetMapping("/menuPermission")
    public String menuPermission(@RequestParam(value="roleId",required = false) String roleId ,Model mv){
        if(!StringUtils.isEmpty(roleId)){
            mv.addAttribute("roleId",roleId);
        }
        return "admin2/system/menu/menu-list";
    }

    //配置菜单权限
    @GetMapping("/operatePermission")
    public String operatePermission(@RequestParam(value="roleId",required = false) String roleId ,Model mv){
        if(!StringUtils.isEmpty(roleId)){
            mv.addAttribute("roleId",roleId);
        }
        return "admin2/system/permission/permission-list";
    }

    //跳转到字典维护页面
    @RequestMapping("/sysDict")
    public String sysDict(Model mv){
        return "admin2/system/sys-dict";
    }

    /**
     * 跳转新增字典数据页面
     */
    @RequestMapping("/gotoAddDictData")
    public String gotoAddDictData(@RequestParam("parentId") Long parentId, Model model){
        model.addAttribute("parentId",parentId);
        return "admin2/system/dict/dict-data-eidt";
    }
    @RequestMapping("/gotoEditDictData")
    public String gotoEditDictData(@RequestParam("dictDataId") Long dictDataId,Model model){
        DictData dictData = dictDataService.get(dictDataId);
        model.addAttribute("dictData",dictData);
        return "admin2/system/dict/dict-data-eidt";
    }

    //跳转到添加字典页面
    @RequestMapping("/addDictUI")
    public String addDictUI(@RequestParam(value="id",required = false)String id, Model mv){
        if(!StringUtils.isEmpty(id)){
            Dict dict = dictService.get(Long.parseLong(id));
            if(dict != null){
                mv.addAttribute("dict",dict);
            }
        }
        return "admin2/system/dict/dict-edit";
    }


    //跳转到角色 添加/修改也页面
    @RequestMapping("/roleEditUI")
    public String roleEditUI(@RequestParam(value="id",required = false)String id, Model mv){
        if(!StringUtils.isEmpty(id)){
            Role role = roleService.get(Long.parseLong(id));
            mv.addAttribute("role",role);
        }
        return "admin2/system/role/role-edit";
    }

    @RequestMapping("/rolePermission")
    public String rolePermission(@RequestParam("userId")Long userId,Model model){
        model.addAttribute("userId",userId);
        return "admin2/system/role/role-list";
    }

    /**
     * 定时任务
     */
    @RequestMapping("/sys-quartz")
    public String sysQuartz(){
        return "admin2/system/sys-quartz";
    }

    @RequestMapping("/quartzEditUI")
    public String quartzEditUI(@RequestParam(value="taskId",required = false) String taskId,Model model){
        if(!StringUtils.isEmpty(taskId)) {
            TimedTask timedTask = timedTaskService.get(taskId);
            model.addAttribute("task", timedTask);
        }
        return "admin2/system/quartz/quartz-edit";
    }


    /**
     * 跳转个人信息
     * @param model
     * @return
     */
    @RequestMapping("/userInfo")
    public String userInfo(Model model){
        model.addAttribute("user",userUtils.getCurrentUser());
        return "admin2/system/user/user-info";
    }


    @RequestMapping("/addMenu")
    @ResponseBody
    @OperateLog(value="添加菜单",module = "菜单模块")
    public Result<Object> addMenu(@RequestBody Menu menu){
        try {
            System.out.println(menu);
            Integer parentId = menu.getParentId();
            if(parentId == null || parentId == -1){
                menu.setLevel(1);
            }
            Menu save = menuService.save(menu);
            return ResultUtil.data(save,"添加成功",200);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("系统错误，错误信息："+e.getMessage());
        }
    }


    @RequestMapping(value = "/getMenu")
    @ResponseBody
    //@OperateLog(value="查询所有一级菜单",module = "菜单模块")
    public Result<Object> getMenus(@RequestParam(value = "spread",required = false) boolean spread,
                                   @RequestParam(value="check",required = false)boolean check,
                                   @RequestParam(value="roleId",required = false) Long roleId){
        List<LayUITree> layUITrees = null;
        List<Menu> menus = menuService.findByLevel(1);
        //List<HashMap<String, Object>> result = new ArrayList<>();    //定义一个map处理json键名问题
        //List<LayUITree> layUITrees = menuUtils.changeTree(menus, spread, check);
        //角色 可访问的菜单
        if(roleId == null){
            layUITrees = layuiTreeUtils.changeTree(menus, true,false);
        }else {
            Role role = roleService.get(roleId);
            List<Menu> roleMenus = role.getMenus();
            layUITrees = layuiTreeUtils.changeTree(menus, roleMenus);
        }
        return ResultUtil.data(layUITrees);
    }


    @RequestMapping(value="/getMenuById")
    @ResponseBody
    //@OperateLog(value="根据ID查询menu",module="菜单模块")
    public Result<Object> getMenuById(Long id){
        Menu menu = menuService.get(id);
        if(menu!=null){
            return ResultUtil.data(menu);
        }
        return ResultUtil.error("未查询到对应的菜单信息！");
    }


    @RequestMapping(value = "/getMenuByParenId")
    @ResponseBody
    //@OperateLog(value="根据父菜单的id",module = "菜单模块")
    public Result<Object> getMenuByParenId(Long id){
        List<Menu> menus = menuService.findByParentId(id.intValue());
        return ResultUtil.data(menus);
    }

    @RequestMapping(value = "/updateMuneById")
    @ResponseBody
    @OperateLog(value = "根据id更新菜单",module = "菜单模块")
    public Result<Object> updateMuneById(@RequestBody Menu menu){
        Integer result = menuService.updateByPrimaryKeySelective(menu);
        if(result > 0){
            return ResultUtil.success("更新成功！");
        }
        return ResultUtil.error("更新失败，请联系管理员处理!");
    }

    @RequestMapping(value = "/deleteMuneByid")
    @ResponseBody
    @OperateLog(value = "根据id删除菜单",module = "菜单模块")
    public Result<Object> deleteMuneByid(@RequestParam(value="menuId",required = true) Long id){
        try {
            menuService.delete(id);
            return ResultUtil.success("更新成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("更新失败，请联系管理员处理!");
        }
    }
    //权限管理
    @GetMapping("sysPermission")
    public String sysPermission(Model model){
        List<Permissions> oneLevelPerList = permissionsService.findByLevel(1);
        model.addAttribute("oneLevelPerList",oneLevelPerList);
        return "admin2/system/sys-permission";
    }

    //角色管理页面
    @GetMapping("sysRole")
    public String sysRole(){
        return "admin2/system/sys-role";
    }


    private Object fun(List<Menu> menu, List<HashMap<String, Object>> result) {
        for(Menu m : menu){
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", m.getId());
            map.put("title", m.getMenuname());
            map.put("spread", true);      //设置是否展开
            List<HashMap<String, Object>> result1 = new ArrayList<>();
            Result<Object> menuByParenId = getMenuByParenId(m.getId());
            List<Menu> children = (List<Menu>)menuByParenId.getResult();
            //如果子菜单不为空，则添加。
            if(!children.isEmpty()) {
                map.put("children", fun(children, result1));
            }
            result.add(map);
        }
        return result;
    }
}
